Introduction to Numpy

In this notebook we'll learn how to use NumPy to work with numerical data.

Import Statements

Understanding NumPy's ndarray

NumPy's most amazing feature is the powerful ndarray.

1-Dimensional Arrays (Vectors)

2-Dimensional Arrays (Matrices)

N-Dimensional Arrays (Tensors)

Challenge:

Hint: You can use the : operator just as with Python Lists.

NumPy Mini-Challenges

Challenge 1: Use .arange()to create a vector a with values ranging from 10 to 29. You should get this:

print(a)

[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29]

Challenge 2: Use Python slicing techniques on a to:

Challenge 3:Reverse the order of the values in a, so that the first element comes last:

[29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]

If you need a hint, you can check out this part of the NumPy beginner's guide

Challenge 4: Print out all the indices of the non-zero elements in this array: [6,0,9,0,0,5,0]

Challenge 5: Use NumPy to generate a 3x3x3 array with random numbers

Hint: Use the .random() function

Challenge 6: Use .linspace() to create a vector x of size 9 with values spaced out evenly between 0 to 100 (both included).

Challenge 7: Use .linspace() to create another vector y of size 9 with values between -3 to 3 (both included). Then plot x and y on a line chart using Matplotlib.

Challenge 8: Use NumPy to generate an array called noise with shape 128x128x3 that has random values. Then use Matplotlib's .imshow() to display the array as an image.

Linear Algebra with Vectors

Broadcasting and Scalars

Matrix Multiplication with @ and .matmul()

Challenge: Let's multiply a1 with b1. Looking at the wikipedia example above, work out the values for c12 and c33 on paper. Then use the .matmul() function or the @ operator to check your work.

Manipulating Images as ndarrays

Challenge: What is the data type of img? Also, what is the shape of img and how many dimensions does it have? What is the resolution of the image?

Challenge: Convert the image to black and white. The values in our img range from 0 to 255.

Challenge: Can you manipulate the images by doing some operations on the underlying ndarrays? See if you can change the values in the ndarray so that:

1) You flip the grayscale image upside down

2) Rotate the colour image

3) Invert (i.e., solarize) the colour image. To do this you need to converting all the pixels to their "opposite" value, so black (0) becomes white (255).

Challenge Solutions

Use your Own Image!

Use PIL to open